package org.example.security.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.core.constant.TokenConstants;
import org.example.core.exception.upload.UploadException;
import org.example.redis.service.RedisService;
import org.example.security.annotation.CountNumber;
import org.example.security.annotation.RequirePermission;
import org.example.security.annotation.RequireRole;
import org.example.security.constant.SecurityRedisConstants;
import org.example.security.handler.SecurityHandler;
import org.example.security.utils.AuthorizeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalTime;
import java.util.concurrent.TimeUnit;

/**
 * @author 小杰_cc
 * @version 1.0
 */
@Aspect
@Component
public class NumberAspect {
    @Autowired
    private RedisService redisService;

    private static final Long timeTotal = 86400L;

    // 环绕切面
    @Around("@annotation(countNumber)")
    public Object numberAround(ProceedingJoinPoint point, CountNumber countNumber) throws Throwable {
        String memberId = SecurityHandler.getData().get(TokenConstants.MEMBER_ID);
        Integer number = redisService.getObject(SecurityRedisConstants.MEMBER_IMAGE + memberId);
        if (number == null){
            // 执行原有逻辑
            Long second = timeTotal - LocalTime.now().toSecondOfDay();
            redisService.setObject(SecurityRedisConstants.MEMBER_IMAGE + memberId, 99, second, TimeUnit.SECONDS);
            return point.proceed();
        }else if (number > 0){
            redisService.setMinus(SecurityRedisConstants.MEMBER_IMAGE + memberId, -1);
            return point.proceed();
        }else {
            throw new UploadException("今日上传次数已到限制");
        }
    }
}
